<template>
  <div class="page-container">
    <div class="page-header">
      <h2>个人资料</h2>
      <p>查看和更新您的个人信息</p>
    </div>

    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :xs="24" :md="16">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" @click="enableEditing" v-if="!editing">
                <el-icon><Edit /></el-icon>
                编辑资料
              </el-button>
              <div v-else>
                <el-button type="primary" @click="saveProfile" :loading="loading">
                  保存
                </el-button>
                <el-button @click="cancelEditing">
                  取消
                </el-button>
              </div>
            </div>
          </template>

          <div v-loading="loading">
            <el-form 
              ref="formRef" 
              :model="form" 
              :rules="rules" 
              label-width="100px"
            >
              <el-row :gutter="20">
                <el-col :xs="24" :md="12">
                  <el-form-item label="用户名">
                    <span v-if="!editing">{{ userInfo.username }}</span>
                    <span v-else class="text-secondary">(用户名不可修改)</span>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="姓名" prop="fullName">
                    <span v-if="!editing">{{ userInfo.fullName }}</span>
                    <el-input v-else v-model="form.fullName" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :xs="24" :md="12">
                  <el-form-item label="邮箱" prop="email">
                    <span v-if="!editing">{{ userInfo.email }}</span>
                    <el-input v-else v-model="form.email" type="email" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="手机号码" prop="phone">
                    <span v-if="!editing">{{ userInfo.phone || '-' }}</span>
                    <el-input v-else v-model="form.phone" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :xs="24" :md="12">
                  <el-form-item label="性别" prop="gender">
                    <span v-if="!editing">{{ getGenderDisplay(userInfo.gender) }}</span>
                    <el-select v-else v-model="form.gender" placeholder="选择性别" style="width: 100%">
                      <el-option label="男" value="MALE" />
                      <el-option label="女" value="FEMALE" />
                      <el-option label="其他" value="OTHER" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="出生日期" prop="birthDate">
                    <span v-if="!editing">{{ formatDate(userInfo.birthDate) }}</span>
                    <el-date-picker
                      v-else
                      v-model="form.birthDate"
                      type="date"
                      placeholder="选择出生日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DDT00:00:00"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="注册时间">
                <span>{{ formatDate(userInfo.registrationDate) }}</span>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>

      <!-- 安全设置卡片 -->
      <el-col :xs="24" :md="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>安全设置</span>
            </div>
          </template>

          <div class="security-options">
            <el-button 
              type="primary" 
              class="security-button" 
              @click="passwordDialogVisible = true"
            >
              <el-icon><Lock /></el-icon>
              修改密码
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form 
        ref="passwordFormRef" 
        :model="passwordForm" 
        :rules="passwordRules" 
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input 
            v-model="passwordForm.currentPassword" 
            type="password" 
            placeholder="输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changePassword" :loading="passwordChanging">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getCurrentUser } from '@/api/auth'
import { updateUserProfile, changePassword as updatePassword } from '@/api/user'

// 表单引用
const formRef = ref(null)
const passwordFormRef = ref(null)

// 状态管理
const userInfo = ref({})
const loading = ref(false)
const editing = ref(false)
const passwordDialogVisible = ref(false)
const passwordChanging = ref(false)

// 表单数据
const form = ref({
  fullName: '',
  email: '',
  phone: '',
  gender: '',
  birthDate: ''
})

// 密码表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
}

// 密码表单验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取性别显示
const getGenderDisplay = (gender) => {
  const genderMap = {
    'MALE': '男',
    'FEMALE': '女',
    'OTHER': '其他'
  }
  return genderMap[gender] || '-'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 启用编辑模式
const enableEditing = () => {
  form.value = {
    fullName: userInfo.value.fullName,
    email: userInfo.value.email,
    phone: userInfo.value.phone || '',
    gender: userInfo.value.gender || '',
    birthDate: userInfo.value.birthDate
  }
  editing.value = true
}

// 取消编辑
const cancelEditing = () => {
  editing.value = false
}

// 保存个人资料
const saveProfile = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    
    try {
      // 准备提交数据
      const submitData = { ...form.value };
      
      // 确保日期格式正确
      if (submitData.birthDate && typeof submitData.birthDate === 'string') {
        // 如果日期不包含T，则转换为ISO格式
        if (!submitData.birthDate.includes('T')) {
          submitData.birthDate = `${submitData.birthDate.split(' ')[0]}T00:00:00`;
        }
      }
      
      const response = await updateUserProfile(submitData)
      userInfo.value = response
      ElMessage.success('个人资料更新成功')
      editing.value = false
    } catch (error) {
      console.error('更新个人资料失败:', error)
      ElMessage.error(error.response?.data?.message || '更新个人资料失败')
    } finally {
      loading.value = false
    }
  })
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    passwordChanging.value = true
    
    try {
      await updatePassword(
        passwordForm.value.currentPassword,
        passwordForm.value.newPassword
      )
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
      
      // 重置表单
      passwordForm.value = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    } catch (error) {
      console.error('修改密码失败:', error)
      ElMessage.error(error.response?.data?.message || '修改密码失败')
    } finally {
      passwordChanging.value = false
    }
  })
}

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true
  
  try {
    userInfo.value = await getCurrentUser()
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.profile-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text-secondary {
  color: #909399;
  font-size: 14px;
}

.security-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.security-button {
  width: 100%;
  justify-content: flex-start;
}

.security-button .el-icon {
  margin-right: 8px;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style> 